package cn.tedu.product.service;

import cn.tedu.product.mapper.ProductMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.common.pojo.Category;
import com.jt.common.pojo.Product;
import com.jt.common.utils.UUIDUtil;
import com.jt.common.vo.EasyUIResult;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class ProductServiceImpl implements ProductService{
    @Autowired(required = false)
    private ProductMapper productMapper;

    @Override
    public EasyUIResult queryByPage(Integer page, Integer rows) {
        EasyUIResult result = new EasyUIResult();
        int total = productMapper.selectCount();
        result.setTotal(total);
        int start = (page-1)*rows;
        List<Product>productList =  productMapper.selectProductByPage(start,rows);

        result.setRows(productList);
        return result;
    }
    @Autowired
    private StringRedisTemplate redisTemplate;
    private static final ObjectMapper mapper = new ObjectMapper();
    @Override
    public Product queryOneProduct(String productId) {
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        //被动查询 被动缓存
        /*
        * 1.生成一个表示的那个商品的redis数据的 key productId+前缀
        * 2.判断缓存是否命中
        * 3.命中数据直接使用productJson
        * 4.未命中查询数据 将数据存放到缓存一份（2天超时）
        * */
        String productKey = "product_"+productId;
        try {
            if(redisTemplate.hasKey(productKey)){
                //readValue pJson
                String productJson = opsForValue.get(productKey);
                return mapper.readValue(productJson,Product.class);
            }else {
                //读数据库
                Product product = productMapper.selectProductById(productId);
                //想缓存存放一份，供后续缓存命中
                //创建value值
                String pJson = mapper.writeValueAsString(product);
                opsForValue.set(productKey,pJson,2, TimeUnit.DAYS);
                return product;
            }

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public Product queryOneProduct(String productId, String userId) {
        Category category = new Category();
        String cat = productMapper.selectProductCategoryByProductId(productId);
        category.setCategory(cat);
        category.setUserId(userId);
        productMapper.insertCategoryByUserId(category);
        return queryOneProduct(productId);
    }

    @Override
    public void addProduct(Product product) {
        String productId = UUIDUtil.getUUID();
        product.setProductId(productId);
        // regis主动缓存
        String productKey = "product_"+productId;
        try {
            String json = mapper.writeValueAsString(product);
            redisTemplate.opsForValue().set(productKey,json,2,TimeUnit.DAYS);
        }catch (Exception e){
            e.printStackTrace();
        }
        productMapper.insertProduct(product);
    }

    @Override
    public void editProduct(Product product) {
        String productKey = "product_"+product.getProductId();
        //缓存也得更新 直接覆盖
        try {
            String json = mapper.writeValueAsString(product);
            redisTemplate.opsForValue().set(productKey,json,2,TimeUnit.DAYS);
        }catch (Exception e){
            e.printStackTrace();
        }
        productMapper.updateProductById(product);
    }

    @Override
    public EasyUIResult recommendProducts() {
        EasyUIResult result = new EasyUIResult();
        int total = productMapper.selectCount();
        int rows = 10;
        int page = new Random().nextInt(total/rows);
        result.setTotal(total);
        int start = page*rows;
        List<Product>productList =  productMapper.selectProductByPage(start,rows);
        result.setRows(productList);
        return result;
    }

    @Override
    public EasyUIResult guessProducts(String userId) {
        EasyUIResult result = new EasyUIResult();
        int total = productMapper.selectCount();
        int rows = 10;
        int page = new Random().nextInt(total/rows)+1;
        result.setTotal(total);
        List<Category> categorus =  productMapper.selectCategoryByUserId(userId);
        for (Category category: categorus
             ) {
            List<Product> productList = productMapper.selectProductByCategory(category);
            result.setRows(productList);
        }
        return result;
    }

    @Test
    public void test01(){
        int page = new Random().nextInt(20/10);
        System.out.println(page);
    }
}
